﻿using System;
using System.Web;
using Funq;
using Microsoft.Practices.Unity;
using ServiceStack.ContainerAdapter.Unity;
using ServiceStack.WebHost.Endpoints;

namespace WebApplication2
{
    public class Global : HttpApplication
    {
        public class ServiceAppHost : AppHostBase
        {
            public ServiceAppHost()
                : base("Order Management", typeof (ServiceAppHost).Assembly)
            {

            }

            public override void Configure(Container container)
            {
                IUnityContainer unityContainer = new UnityContainer();

                //Default: TransientLifetimeManager
                unityContainer.RegisterType<IProductRepository, ProductRepository>();

                //Per resolve (new instance for ever "Resolve")
                //unityContainer.RegisterType<IProductRepository, ProductRepository>(new TransientLifetimeManager());

                //Per resolve (new instance for ever "Resolve")
                //unityContainer.RegisterType<IProductRepository, ProductRepository>(new PerResolveLifetimeManager());

                //Singleton
                //unityContainer.RegisterType<IProductRepository, ProductRepository>(new ContainerControlledLifetimeManager());

                //Per Request Manager.
                //unityContainer.RegisterType<IProductRepository, ProductRepository>(new PerRequestLifetimeManager());
                container.Adapter = new UnityContainerAdapter(unityContainer);
            }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            new ServiceAppHost().Init();
        }
    }

    public class PerRequestLifetimeManager : LifetimeManager
    {
        private readonly object key = new object();

        public override object GetValue()
        {
            if (HttpContext.Current != null &&
                HttpContext.Current.Items.Contains(key))
                return HttpContext.Current.Items[key];
            else
                return null;
        }

        public override void RemoveValue()
        {
            if (HttpContext.Current != null)
                HttpContext.Current.Items.Remove(key);
        }

        public override void SetValue(object newValue)
        {
            if (HttpContext.Current != null)
                HttpContext.Current.Items[key] = newValue;
        }
    }
}